use serde::{Deserialize, Serialize};
use std::net::UdpSocket;

#[derive(Serialize, Deserialize)]
pub struct UdpConfig {
    pub host: String,
    pub port: u16,
}

#[derive(Serialize, Deserialize)]
pub struct PlaySceneCommand {
    pub scene_number: u32,
}

//#[derive(Serialize, Deserialize)]
//pub struct StopPlayingCommand {}

//#[derive(Serialize, Deserialize)]
//pub struct ShutdownComputerCommand {}

//const COMMAND_PLAY: u32 = 0x00000001;
//const COMMAND_STOP: u32 = 0x00000003;
//const COMMAND_SHUTDOWN: u32 = 0x0000000A;

#[tauri::command]
pub fn play_scene(config: UdpConfig, command: PlaySceneCommand) -> Result<String, String> {
    let socket = UdpSocket::bind("0.0.0.0:0").map_err(|e| e.to_string())?;
    let target_addr = format!("{}:{}", config.host, config.port);
    
    // 构建数据包: 命令长度(4字节小端) + 命令1(4字节小端) + 场景号(4字节小端)
    // 格式: 0x0c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, xx, xx, xx, xx
    let mut data = vec![0x0c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
    
    // 设置场景号 (小端字节序)
    let scene_bytes = command.scene_number.to_le_bytes();
    data[8] = scene_bytes[0];
    data[9] = scene_bytes[1];
    data[10] = scene_bytes[2];
    data[11] = scene_bytes[3];
    
    socket.send_to(&data, target_addr).map_err(|e| e.to_string())?;
    
    Ok(format!("播放场景 {} 命令已发送", command.scene_number))
}

#[tauri::command]
pub fn stop_playing(config: UdpConfig) -> Result<String, String> {
    let socket = UdpSocket::bind("0.0.0.0:0").map_err(|e| e.to_string())?;
    let target_addr = format!("{}:{}", config.host, config.port);
    
    // 构建数据包: 命令长度(4字节小端) + 命令3(4字节小端)
    // 格式: 0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00
    let data = vec![0x08, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00];
    
    socket.send_to(&data, target_addr).map_err(|e| e.to_string())?;
    
    Ok("结束播放命令已发送".to_string())
}
